import useMessage from "@/hooks/useMessage";
import { Form, Button, Input, FormInstance } from "antd";
import React, { useEffect, useRef } from "react";
import styles from "./index.module.less";
import { addTag, updateTag } from "@/redux/modules/tag/action";
import { Tag } from "@/api/interface/tag";
import { RootState } from "@/redux";
import { useSelector } from "react-redux";

interface PropsType {
	type?: string;
	onComfirm?: () => void;
}

const TagAdd: React.FC<PropsType> = props => {
	const { type, onComfirm } = props;
	const { contextHolder, success } = useMessage();

	const formRef = useRef<FormInstance | null>(null);

	const onFinish = async (tag: Tag) => {
		if (type) {
			updateTag({ ...tag, id: tagDetail.id + "" } as any);
		} else {
			addTag(tag);
		}
		onComfirm && onComfirm();
		success("发布成功");
	};

	const tagDetail = useSelector((state: RootState) => state.tag.tagDetail);

	useEffect(() => {
		if (type) formRef.current?.resetFields();
	}, [tagDetail]);

	useEffect(() => {
		return () => {
			formRef.current?.setFieldsValue({
				tag_name: "",
				tag_classify: ""
			});
		};
	});

	return (
		<div className={styles.root}>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={tagDetail}
			>
				<Form.Item label="标签名" rules={[{ required: true }]} name="tag_name">
					<Input />
				</Form.Item>
				<Form.Item label="标签类别" rules={[{ required: true }]} name="tag_classify">
					<Input />
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default TagAdd;
